package com.mz.ozy.activity.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.mz.ozy.R;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AlipayAuthBean;
import com.mz.ozy.bean.CheckBean;
import com.mz.ozy.bean.LoginBean;
import com.mz.ozy.mvp.presenter.LoginPresenter;
import com.mz.ozy.mvp.view.LoginContract;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.socks.library.KLog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by administrator on 2018/11/21.
 * 首要登录页面
 */
public class LoginActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {


    @BindView(R.id.ll_wechat_login)
    LinearLayout mLlWechatLogin;
    @BindView(R.id.tv_phone_login)
    TextView mTvPhoneLogin;
    @BindView(R.id.alipayIv)
    ImageView mAlipayIv;
    @BindView(R.id.tv_service_agreement)
    TextView mTvServiceAgreement;
    @BindView(R.id.tv_privacy_policy)
    TextView mTvPrivacyPolicy;

    //微信授权数据
    private String unionId;
    private String wx_useravatar;
    private String wx_nickname;
    private String wx_sex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_login);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_wechat_login, R.id.tv_phone_login, R.id.alipayIv, R.id.tv_service_agreement, R.id.tv_privacy_policy, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wechat_login:
                showDialog();
                break;
            case R.id.tv_phone_login:
                startActivity(new Intent(this, PhoneSmsLoginActivity.class));
                finish();
                break;
            case R.id.alipayIv:
                mPresenter.onGetAlipayAuth(this);
                break;
            case R.id.tv_service_agreement:
                AgreementActivity.go(this, 1);
                break;
            case R.id.tv_privacy_policy:
                AgreementActivity.go(this, 2);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void showDialog() {
        final BaseDialog dialog = new BaseDialog(this, R.layout.dialog_open_wx, Gravity.CENTER, true);
        dialog.setOnViewClick(R.id.tv_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onWxAuth(SHARE_MEDIA.WEIXIN);
                dialog.toggleDialog();
            }
        }).setOnViewClick(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
            }
        });
        dialog.toggleDialog();
    }

    /**
     * 登录成功
     *
     * @param loginBean
     */
    @Override
    public void onLoginSuccess(LoginBean loginBean) {
        String uid = loginBean.getUid();
//        if (!TextUtils.isEmpty(uid)){
//            Constants.uid = uid;
//            AppUtils.saveUid(this, uid);
//        }
        //判断是否是初次登录
//        if(loginBean.getIsFirstLogin() == 1){
//            startActivity(new Intent(this,SportsSurveyActivity1.class));
//        }else{
//            Intent intent = new Intent(this, MainTabActivity.class);
//            intent.putExtra(MainTabActivity.IS_LOGIN_TYPE, true);
//            startActivity(intent);
//        }
//        finish();
    }

    @Override
    public void onGetAlipayAuthSuccess(String sdkUrl) {
        onAliPayAuth(sdkUrl);
    }

    @Override
    public void onNeedBindPhone(int type, AlipayAuthBean bean) {
//        if(type==LoginPresenter.AUTH_TYPE_WX){
//            BindPhoneActivity.go(LoginActivity.this,type,unionId,wx_useravatar,wx_nickname,wx_sex);
//        }else if(type == LoginPresenter.AUTH_TYPE_ALIPAY){
//            BindPhoneActivity.go(LoginActivity.this,type,bean.getUserId(),bean.getAvatar(),bean.getNick_name(),bean.getGender());
//        }
    }

    @Override
    public void checkUpdateVersionSuccess(CheckBean o) {

    }


    /**************************************  微信授权  *****************************************/
    /**
     * 微信授权
     *
     * @param
     */
    private void onWxAuth(SHARE_MEDIA share_media) {
        //最新版本微信客户端调用接口后也不再出现授权确认页面，确认在微信客户端切换账号后，
        //再次调用登录接口获取的用户资料变化即可
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);

        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                KLog.e("onStart()  微信授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                KLog.e("onComplete() 成功");
                //微信返回的openID和unionID都可以实现用户标识的需求，二者的区别在于，unionID可以实现同一个开发者账号下的应用之间账号打通的需求

                unionId = map.get("uid");     //就是unionid，友盟封装了
                wx_nickname = map.get("name");        //名字
                String gender = map.get("gender");    //性别
                wx_useravatar = map.get("iconurl");  //头像
                if ("男".equals(gender)) {
                    wx_sex = "1";
                } else {
                    wx_sex = "0";
                }
                mPresenter.onAuthLogin(LoginActivity.this, LoginPresenter.AUTH_TYPE_WX, "", unionId);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastUtils.showToast("授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtils.showToast("授权取消");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
    /**************************************  微信授权  *****************************************/

    /************************************* 支付宝授权 *****************************************/
    public void onAliPayAuth(final String authInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);


                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> authResult = (HashMap<String, String>) msg.obj;

                    String resultStatus = authResult.get("resultStatus");
                    KLog.e("authResult", authResult.toString());
                    if (TextUtils.equals(resultStatus, "9000")) { //授权成功
                        String result = authResult.get("result");
                        //截取auth_code=之后的字符串
                        String str = result.substring(result.indexOf("auth_code="));
                        //截取&之前的字符串
                        String str2 = str.substring(0, str.indexOf("&"));
                        String auth_code = str2.replace("auth_code=", "");
                        mPresenter.onAuthLogin(LoginActivity.this, LoginPresenter.AUTH_TYPE_ALIPAY, auth_code, "");
                    } else {
                        ToastUtils.showToast("授权失败");
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    /************************************* 支付宝授权 *****************************************/
}
